using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Data;

namespace DataAccess.Handlers
{
    public class DataHandler : IDataHandler
    {
        private IList<IDataHandler> mHandlers;

        public IList<IDataHandler> Handlers
        {
            get
            {
                return mHandlers;
            }
        }

        public DataHandler()
        {
            mHandlers = new List<IDataHandler>();
        }

        public bool Process(object entity, string table)
        {
            if (entity != null)
            {
                return Process(entity, entity.GetType().GetProperties(), table);
            }
            else
            {
                return true;
            }
        }

        public bool Process(object entity, DataRow row, string table)
        {
            if (entity != null)
            {
                return Process(entity, entity.GetType().GetProperties(), row, table);
            }
            else
            {
                return true;
            }
        }

        public bool Process(object entity, PropertyInfo[] properties, string table)
        {
            bool result = true;
            if (entity != null)
            {
                foreach (IDataHandler item in mHandlers)
                {
                    result = item.Process(entity, properties, table);
                    if (result == false) break;
                }
            }
            return result;
        }

        public bool Process(object entity, PropertyInfo[] properties, DataRow row, string table)
        {
            bool result = true;
            if (entity != null)
            {
                foreach (IDataHandler item in mHandlers)
                {
                    result = item.Process(entity, properties, row, table);
                    if (result == false) break;
                }
            }
            return result;
        }

        public void Add(IDataHandler handler)
        {
            bool exist = false;
            foreach (IDataHandler i in this.Handlers)
            {
                if (handler.GetType() == i.GetType())
                {
                    exist = true;
                    break;
                }
            }
            if (!exist)
            {
                this.Handlers.Add(handler);
            }
        }
    }
}
